package biznussoft.metercor.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import biznussoft.metercor.HomeActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.listeners.GlobalListener;
import biznussoft.metercor.lookup.AccountLookup;
import biznussoft.metercor.model.Bean_Class;
import biznussoft.metercor.model.ContactsModel;
import biznussoft.metercor.utils.Session;

import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class ContactDetailsFragment  extends BaseFragment implements OnClickListener {
	
	private ScrollView svContact,svContactdetails;
	public static EditText etContactAccountName;
	private EditText etMaillingCity,etMaillingStreet,etMailingCountry,etMaillingstate,etMaillingZip,etOtherCity,etOtherStreet,etOtherState,etOtherCountry,etOtherZip,etFirstName,etLastName,etTitle,etContactphone,etMobile,etEmail,etDescription;
	private TextView  tvContactBillingToShipping,tvMaillingCity,tvMaillingStreet,tvMailingCountry,tvMaillingstate,tvMaillingZip,tvContactAccountName,tvOtherCity,tvOtherStreet,tvOtherState,tvOtherCountry,tvOtherZip,
	tvFirstName,tvLastName,tvTitle,tvContactphone,tvMobile,tvEmail,tvDescription,tvAccountName;
	private RestClient client;
	private Button mContactSave,mCancel;
	private Spinner mType,mIndustry,mRating,mOwnerShip,etLeadSource;
	private Bundle args2;
	private String parantAccountID;
	static ArrayList<ContactsModel> contactList;
	private ContactsModel model;
	private boolean flag;
	private GlobalListener mHomeItemListener;   
	private MenuItem edit,logout;
	private int mPosition ;
	private String mCategory;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.contact_details_fragment, null);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mHomeItemListener = (GlobalListener) (activity);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		edit = menu.add("Edit");                 
		MenuItemCompat.setShowAsAction(edit,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		edit.setIcon(R.drawable.edit); 
		logout = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(logout,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		logout.setIcon(R.drawable.logout); 

		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getTitle().equals("Logout")) {
			SalesforceSDKManager.getInstance().logout(getActivity());
		}
		if (item.getTitle().equals("Edit")) {
			edit.setVisible(false);
			editAccount();
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		svContactdetails = (ScrollView) getView().findViewById(R.id.contactdetails);
		svContact = (ScrollView) getView().findViewById(R.id.contactScrooview);
		mContactSave = (Button) getView().findViewById(R.id.btSave2);
		mCancel = (Button) getView().findViewById(R.id.btCancel2);
		mType = (Spinner) getView().findViewById(R.id.etType);
		mRating = (Spinner) getView().findViewById(R.id.etRating);
		mIndustry = (Spinner) getView().findViewById(R.id.etIndustry);
		mOwnerShip = (Spinner) getView().findViewById(R.id.etOwnership);
		tvContactBillingToShipping = (TextView)getView().findViewById(R.id.tvCopyContactBillingToShipping);
		
		
		tvContactBillingToShipping.setOnClickListener(this);
		mContactSave.setOnClickListener(this);    
		mCancel.setOnClickListener(this);
		
		etMailingCountry = (EditText) getView().findViewById(R.id.etMailingcountry);
		etMaillingCity = (EditText) getView().findViewById(R.id.etMailingcity);
		etMaillingstate = (EditText) getView().findViewById(R.id.etMailingState);
		etMaillingStreet = (EditText) getView().findViewById(R.id.etMailingStreet);
		etMaillingZip = (EditText) getView().findViewById(R.id.etMailingcode);
		etContactAccountName = (EditText) getView().findViewById(R.id.etContactAccountName);
		etContactAccountName.setOnClickListener(this);
		
		etOtherCity = (EditText) getView().findViewById(R.id.etOtherCity);
		etOtherCountry = (EditText) getView().findViewById(R.id.etOthercountry);
		etOtherState = (EditText) getView().findViewById(R.id.etOtherState);
		etOtherStreet = (EditText) getView().findViewById(R.id.etOtherstreet);
		etOtherZip = (EditText) getView().findViewById(R.id.etOthercode);
		etFirstName = (EditText) getView().findViewById(R.id.etFirstname);
		etLastName = (EditText) getView().findViewById(R.id.etLastname);
		etTitle = (EditText) getView().findViewById(R.id.etTite);
		etMobile = (EditText) getView().findViewById(R.id.etMobile);
		etEmail = (EditText) getView().findViewById(R.id.etEmail);
		etContactphone = (EditText) getView().findViewById(R.id.etContactPhone);
		etLeadSource = (Spinner) getView().findViewById(R.id.etLeadSource);
		etDescription = (EditText) getView().findViewById(R.id.etDescription);
				
		
		tvMailingCountry = (TextView) getView().findViewById(R.id.tvMailingcountry);
		tvMaillingCity = (TextView) getView().findViewById(R.id.tvMailingcity);
		tvMaillingstate = (TextView) getView().findViewById(R.id.tvMailingState);
		tvMaillingStreet = (TextView) getView().findViewById(R.id.tvMailingStreet);
		tvMaillingZip = (TextView) getView().findViewById(R.id.tvMailingcode);
		tvContactAccountName = (TextView) getView().findViewById(R.id.tvContactAccountName);
		tvOtherCity = (TextView) getView().findViewById(R.id.tvOtherCity);
		tvOtherCountry = (TextView) getView().findViewById(R.id.tvOthercountry);
		tvOtherState = (TextView) getView().findViewById(R.id.tvOtherState);
		tvOtherStreet = (TextView) getView().findViewById(R.id.tvOtherstreet);
		tvOtherZip = (TextView) getView().findViewById(R.id.tvOthercode);
		tvFirstName = (TextView) getView().findViewById(R.id.tvFirstname);
		tvLastName = (TextView) getView().findViewById(R.id.tvLastname);
		tvAccountName = (TextView) getView().findViewById(R.id.tvContactAccountName);
		tvTitle = (TextView) getView().findViewById(R.id.tvTite);
		tvMobile = (TextView) getView().findViewById(R.id.tvMobile);
		tvEmail = (TextView) getView().findViewById(R.id.tvEmail);
		tvContactphone = (TextView) getView().findViewById(R.id.tvContactPhone);
		
		
		
		client = HomeActivity.mActivity.client;
		
		
		 args2 = getArguments();
		 if (args2 != null) {                 


			 if(args2.getInt("Position")== 1){
				 svContactdetails.setVisibility(View.VISIBLE);
				 svContact.setVisibility(View.GONE);
				 parantAccountID =args2.getString("AccountId");

			 }else{
				 svContact.setVisibility(View.VISIBLE);
				 svContactdetails.setVisibility(View.GONE);
				 etMailingCountry.setText(args2.getString("MailingCountry"));
				 etMaillingCity.setText(args2.getString("MaillingCity"));
				 etMaillingstate.setText(args2.getString("Maillingstate"));
				 etMaillingStreet.setText(args2.getString("MaillingStreet"));
				 etMaillingZip.setText(args2.getString("MaillingZip"));
				 etContactphone.setText(args2.getString("Contactphone"));
				 etContactAccountName.setText(args2.getString("ContactAccountName"));
				 parantAccountID = args2.getString("AccountId");
			 }


		 }
        
	}

	
	public void showContacts(int position,String category){
		
		mPosition = position;
		mCategory = category;
		svContactdetails.setVisibility(View.VISIBLE);
		svContact.setVisibility(View.GONE);
		
		if(category.equalsIgnoreCase("accounts")){
		 model = AccountsFragment.contactsList.get(position);}
		else{
			 model = ContactsFragment.contactList.get(position);	
		}
		tvAccountName.setText(Session.sAccountName);                    
		tvLastName.setText(model.getLastName());           
		tvFirstName.setText(model.getFirstName());
		tvContactphone.setText(model.getPhone());
		tvMaillingCity.setText(model.getMailingCity());
		tvMailingCountry.setText(model.getMailingCountry());
		tvMaillingZip.setText(model.getMailingPostalCode());
		tvMaillingstate.setText(model.getMailingState());
		tvMaillingStreet.setText(model.getMailingStreet());
		tvOtherCity.setText(model.getOtherCity());
		tvOtherCountry.setText(model.getOtherCountry());
		tvOtherZip.setText(model.getOtherPostalCode());      
		tvOtherState.setText(model.getOtherState());
		tvOtherStreet.setText(model.getOtherStreet());
		tvEmail.setText(model.getEmail());
		tvMobile.setText(model.getMobilePhone());   
		tvTitle.setText(model.getTitle());
	
		parantAccountID =model.getId();
	
		
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {          
		
		case R.id.etContactAccountName:
			AccountLookup lookup = new AccountLookup();
//			lookup.accountLookupDetails(getActivity(),"contact");
			break;
		case R.id.btSave2:
			if (!flag) {
				createContact();
			} else {
				updateContact(parantAccountID);
			}
			break;
			
		case R.id.tvCopyContactBillingToShipping:
			String MaillingCity = etMaillingCity.getText().toString();
			if (MaillingCity != null) {
				etOtherCity.setText(MaillingCity);
			}
			String MailingCountry = etMailingCountry.getText().toString();
			if (MailingCountry != null) {
				etOtherCountry.setText(MailingCountry);
			}

			String MailingZip = etMaillingZip.getText().toString();
			if (MailingZip != null) {
				etOtherZip.setText(MailingZip);
			}
			String MailingState = etMaillingstate.getText().toString();
			if (MailingState != null) {
				etOtherState.setText(MailingState);
			}
			String MailingStreet = etMaillingStreet.getText().toString();
			if (MailingStreet != null) {
				etOtherStreet.setText(MailingStreet);
			}
			
			break;
	
		case R.id.btCancel2:
			showContacts(mPosition,mCategory);
			break;
		default:
			break;
		}
	}
	
	public void editAccount(){
		flag = true; 
		svContact.setVisibility(View.VISIBLE);
    	svContactdetails.setVisibility(View.GONE);
    	etLastName.setText(model.getLastName());           
    	etFirstName.setText(model.getFirstName());
    	etContactphone.setText(model.getPhone());
		etMaillingCity.setText(model.getMailingCity());
		etMailingCountry.setText(model.getMailingCountry());
		etMaillingZip.setText(model.getMailingPostalCode());
		etMaillingstate.setText(model.getMailingState());
		etMaillingStreet.setText(model.getMailingStreet());
		etOtherCity.setText(model.getOtherCity());
		etOtherCountry.setText(model.getOtherCountry());
		etOtherZip.setText(model.getOtherPostalCode());      
		etOtherState.setText(model.getOtherState());
		etOtherStreet.setText(model.getOtherStreet());
		etEmail.setText(model.getEmail());
		etMobile.setText(model.getMobilePhone());   
		etTitle.setText(model.getTitle());
			
	}
	
	public void createContact(){
		{
			String objectType = "Contact";
			HashMap<String, Object> fields = new HashMap<String, Object>();
			
			fields.put("AccountId",Session.sParentId);
			fields.put("FirstName",etFirstName.getText().toString());
			fields.put("LastName",etLastName.getText().toString());
			fields.put("Phone",etContactphone.getText().toString());
			fields.put("MailingCity",etMaillingCity.getText().toString());
			fields.put("MailingState",etMaillingstate.getText().toString());
			fields.put("MailingCountry", etMailingCountry.getText().toString());
			fields.put("MailingPostalCode", etMaillingZip.getText().toString());
			fields.put("MailingStreet", etMaillingStreet.getText().toString());
			fields.put("OtherCity", etOtherCity.getText().toString());
			fields.put("OtherCountry",etOtherCountry.getText().toString());
			fields.put("OtherPostalCode",etOtherZip.getText().toString());
			fields.put("OtherState",etOtherState.getText().toString());
			fields.put("OtherStreet",etOtherStreet.getText().toString());
			fields.put("Email",etEmail.getText().toString());
			fields.put("MobilePhone",etMobile.getText().toString());
			fields.put("Title",etTitle.getText().toString());
			fields.put("LeadSource", etLeadSource.getSelectedItem().toString());
			fields.put("Description", etDescription.getText().toString());
			
			try {
			    RestRequest restRequest = RestRequest.getRequestForCreate(Bean_Class.api_Version,objectType,fields);
			    
			    
			    client.sendAsync(restRequest, new AsyncRequestCallback() {
					@Override
					public void onSuccess(RestRequest request, RestResponse result) {
						try {     
							
							JSONObject json = new JSONObject(result.toString());
							if(json!= null){
								if(json.getString("success").equalsIgnoreCase("true")){
									mHomeItemListener.onCategoryClicked(-2);
								}
								
							}
						
							
							}                                
						catch (Exception exception) {
							
						}
					}
					
					//@Override
					public void onError(Exception exception) {
						 Toast.makeText(getActivity(),
			                		ContactDetailsFragment.this.getString(SalesforceSDKManager.getInstance().getSalesforceR().stringGenericError(), exception.toString()),
			                               Toast.LENGTH_LONG).show();
						EventsObservable.get().notifyEvent(EventType.RenditionComplete);
					}
				});             
			} 
			catch (Exception e) {
				Log.i("NCS","Exception is   :"+e.getMessage());
			    
			}

		}
		
		
	}
	
	public void updateContact(String id){
		{
			
			String objectType = "Contact";
			HashMap<String, Object> fields = new HashMap<String, Object>();
			fields.put("AccountId",Session.sParentId);
			fields.put("FirstName",etFirstName.getText().toString());
			fields.put("LastName",etLastName.getText().toString());
			fields.put("Phone",etContactphone.getText().toString());
			fields.put("MailingCity",etMaillingCity.getText().toString());
			fields.put("MailingState",etMaillingstate.getText().toString());
			fields.put("MailingCountry", etMailingCountry.getText().toString());
			fields.put("MailingPostalCode", etMaillingZip.getText().toString());
			fields.put("MailingStreet", etMaillingStreet.getText().toString());
			fields.put("OtherCity", etOtherCity.getText().toString());
			fields.put("OtherCountry",etOtherCountry.getText().toString());
			fields.put("OtherPostalCode",etOtherZip.getText().toString());
			fields.put("OtherState",etOtherState.getText().toString());
			fields.put("OtherStreet",etOtherStreet.getText().toString());
			fields.put("Email",etEmail.getText().toString());
			fields.put("MobilePhone",etMobile.getText().toString());
			fields.put("Title",etTitle.getText().toString());
			fields.put("LeadSource", etLeadSource.getSelectedItem().toString());
			fields.put("Description", etDescription.getText().toString());
			
			try {
				  RestRequest restRequest = RestRequest.getRequestForUpdate(Bean_Class.api_Version,objectType,id,fields);
			    
			    
			    client.sendAsync(restRequest, new AsyncRequestCallback() {
					@Override
					public void onSuccess(RestRequest request, RestResponse result) {
						try {     
							showContacts(mPosition,mCategory);
							JSONObject json = new JSONObject(result.toString());
							if(json!= null){
								if(json.getString("success").equalsIgnoreCase("true")){
									mHomeItemListener.onCategoryClicked(-2);
								}
								
							}
						
							
							}                                
						catch (Exception exception) {
							
						}
					}
					
					//@Override
					public void onError(Exception exception) {
						 Toast.makeText(getActivity(),
			                		ContactDetailsFragment.this.getString(SalesforceSDKManager.getInstance().getSalesforceR().stringGenericError(), exception.toString()),
			                               Toast.LENGTH_LONG).show();
						EventsObservable.get().notifyEvent(EventType.RenditionComplete);
					}
				});
			} 
			catch (Exception e) {
				Log.i("NCS","Exception is   :"+e.getMessage());
			    
			}

		}
		
		
	}
	
	
	
}
